import useSWR from 'swr';
import { locationSpaceUsageApi } from '../api/dashboard';
import { useAuthStore2 } from '../store/useAuthStore2';
import dayjs from 'dayjs';

export const useBarData = () => {
  const token = useAuthStore2((s) => s.token);
  console.log('token------wms', token);
  const { data, error, isLoading } = useSWR(
    () => (token ? '/report/large-screen/statistics-locationSpaceUsage' : null),
    locationSpaceUsageApi,  // 
  );

  const barData: {
    xAxis: string[];
    seriesData: {
      name: string;
      data: number[];
      labelColor: string;
    }[];
  } = {
    xAxis: [],
    seriesData: [
      {
        name: '总库位',
        data: [],
        labelColor: '#D8D8D8',
      },
      {
        name: '存储库位',
        data: [],
        labelColor: 'rgba(226, 143, 37, 1)',
      },
      {
        name: '拣货库位',
        data: [],
        labelColor: 'rgba(3, 182, 195, 1)',
      },
    ],
  };

  const startDate = dayjs().subtract(2, 'month').format('YYYY-MM-DD HH:mm:ss');

  const formatNumber = (num: number) => (num ? parseInt(num.toString()) : 0);

  barData.xAxis =
    data?.totalLocationList
      ?.filter((i) => !dayjs(i.day + '00:00:00').isBefore(startDate))
      .map((i) => i.week || '')
      .sort(function (a, b) {
        return (
          new Date(a + ':00:00').getTime() - new Date(b + ':00:00').getTime()
        );
      }) || [];
  
    let pathname = typeof window !== 'undefined' && window.location.pathname;
  if (pathname && pathname.includes('/web/cx')) {
    // 城西仓 没有 存储库位
    barData.seriesData.splice(1, 1);
    barData.seriesData[0].data = barData.xAxis.map((i) => {
      const item = data?.totalLocationList?.find((item) => item.week === i);
      return item?.quantity1 ? formatNumber(item?.quantity1) : 0;
    });
    barData.seriesData[1].data = barData.xAxis.map((i) => {
      const item = data?.pickLocationList?.find((item) => item.week === i);
      return item?.quantity1 ? formatNumber(item?.quantity1) : 0;
    });
  } else { 
      barData.seriesData[0].data = barData.xAxis.map((i) => {
        const item = data?.totalLocationList?.find((item) => item.week === i);
        return item?.quantity1 ? formatNumber(item?.quantity1) : 0;
      });

      barData.seriesData[1].data = barData.xAxis.map((i) => {
        const item = data?.backupLocationList?.find((item) => item.week === i);
        return item?.quantity1 ? formatNumber(item?.quantity1) : 0;
      });

      barData.seriesData[2].data = barData.xAxis.map((i) => {
        const item = data?.pickLocationList?.find((item) => item.week === i);
        return item?.quantity1 ? formatNumber(item?.quantity1) : 0;
      });
  }



  return {
    barData,
    isLoading,
    isError: error,
  };
};
